********************************************************************************

* T�tulo da pesquisa: Estrutura de Capital e Mecanismos de Governan�a Externos � Firma: Uma An�lise Multipa�s
* Fl�via Mendon�a, Henrique Castro Martins, Paulo Renato Soares Terra
* Data: Setembro de 2019
* Journal: RAC - Revista de Administra��o Contempor�nea / RAC-2019-0109

********************************************************************************
* setup
cap log close									/* Fechar log existentes */
log using "1RAC 2019 0109.smcl" , replace		/* Abrir novo arquivo log */
use "1RAC 2019 0109" , clear					/* Usar base de dados */
xtset id_firm year								/* Estrutura em painel */



********************************************************************************
* Ajustes nomes dos pa�ses
replace country = "Austr�lia"   	if     country =="Austr�lia"
replace country = "B�lgica"   		if     country =="B�lgica"
replace country = "Canad�"   		if     country =="Canad�"
replace country = "Col�mbia"   		if     country =="Col�mbia"
replace country = "Finl�ndia"   	if     country =="Finl�ndia"
replace country = "Fran�a"   		if     country =="Fran�a"
replace country = "Gr�cia"   		if     country =="Gr�cia"                    
replace country = "Indon�sia"   	if     country =="Indon�sia"                    
replace country = "It�lia"   		if     country =="It�lia"                    
replace country = "Jap�o"   		if     country =="Jap�o"                    
replace country = "Jord�nia"   		if     country =="Jord�nia"                    
replace country = "Mal�sia"   		if     country =="Mal�sia"                    
replace country = "M�xico"   		if     country =="M�xico"                    
replace country = "Nova Zel�ndia"   if     country =="Nova Zel�ndia"                    
replace country = "Pa�ses Baixos"   if     country =="Pa�ses Baixos"                    
replace country = "Sri Lanka"   	if     country =="Sri Lanca"                    
replace country = "Su��a"   		if     country =="Sui�a"                    
replace country = "Su�cia"   		if     country =="Su�cia"                    
replace country = "Tail�ndia"   	if     country =="Tail�ndia"                    
replace country = "�frica do Sul"   if     country =="�frica do Sul"                    
replace country = "�ustria"   		if     country =="�ustria"      
replace country = "Sri Lanka" 		if 		country=="Sri Lanca"

* Define a posi��o do label de cada pa�s para cria��o dos gr�ficos finais
gen pos = 3
replace pos = 3 if country=="Canad�"
replace pos = 1 if country=="Hong Kong"
replace pos = 10 if country=="Su��a"
replace pos = 9 if country=="Jap�o"
replace pos = 5 if country=="B�lgica"
replace pos = 1 if country=="Sri Lanka"
replace pos = 9 if country=="Fran�a"
replace pos = 9 if country=="Equador"
replace pos = 9 if country=="M�xico"
replace pos = 12 if country=="Brasil"
replace pos = 9 if country=="Peru"
replace pos = 9 if country=="Noruega"
replace pos = 9 if country=="Pa�ses Baixos"
replace pos = 3 if country=="Tail�ndia"
replace pos = 9 if country=="Dinamarca"
replace pos = 5 if country=="�frica do Sul"
replace pos = 9 if country=="Israel"              


*******************************************************************************

* Cria��o dos fatores de prote��o aos investidores
sort country -year
bys id_country  : gen id = _n

* Prote��o ao acionista minorit�rio [0,1]
gen f_mdiv			=mdiv
gen f_selfdealing	=selfdealing
gen f_adri_rev		=adri_rev
gen f_disclosure	=disclosure
gen f_standard		=standard

sum f_*

* normaliza��o entre [0,1]														
foreach var in f_adri_rev {
	qui sum `var'
	replace `var' = (`var' - `r(min)') / (`r(max)'-`r(min)')
	}	
gen fshar = f_mdiv + f_selfdealing + f_adri_rev + f_disclosure + f_standard
sum f_mdiv  f_selfdealing  f_adri_rev  f_disclosure  f_standard

* Prote��o ao credor [0,1]
gen f_creditor_rights_rev	=creditor_rights_rev
gen f_legalreserve			=legalreserve
gen f_recovery_rate			=recovery_rate
gen f_enforcement			=enforcement
gen f_sharing				=sharing

* normalizando entre [0,1]
foreach var in f_creditor_rights_rev  f_enforcement f_recovery_rate f_legalreserve{
	sum `var' , d
	replace `var' = (`var' - `r(min)') / (`r(max)'-`r(min)')
	}	
	
gen fcred = f_creditor_rights_rev + f_legalreserve + f_recovery_rate + f_enforcement + f_sharing
sum f_creditor_rights_rev  f_legalreserve  f_recovery_rate  f_enforcement  f_sharing

sum fshar fcred			 , d
sum fshar fcred if id==1 , d

* C�lculo da mediana de protecao aos investidores

egen fsharmed 		= median(fshar) if id==1
egen fcredmed		= median(fcred) if id==1

sum  fsharmed , d
global 	medshar 	= `r(p50)'
gen 	medshar 	= `r(p50)'

sum  	fcredmed  , d
global 	medcred 	= `r(p50)'
gen 	medcred  	= `r(p50)'

* Cria��o dos gr�ficos 
twoway scatter fcred fshar if id==1, mlabel(country) mlabv(pos) mlabp(6) mlabsize(vsmall) msize(small)  msymbol(o) yline($medcred) xline($medshar) ytitle(Direito dos Credores) xtitle(Prote��o aos Acionistas Minorit�rios) graphregion(color(white)) xsc(r(0.5(.25)4)) xlabel(0.5(0.5)4) ysc(r(1(0.25)4.5)) ylabel(1(0.5)4.5,nogrid) text(4.4 3.8 "HH", place(e)) text(4.4 0.6 "LH", place(e)) text(1.1 0.6 "LL", place(e)) text(1.1 3.8 "HL", place(e))
graph save "1RAC 2019 0109 Graph1" , replace

* Cria��o das dummies de prote��o aos investidores

gen 	D_credor = 1 
replace D_credor = 0 if fcred < medcred

gen 	D_acionista = 1 
replace D_acionista = 0 if fshar < medshar

gen D_HH = 0
replace D_HH = 1 if D_credor == 1 & D_acionista == 1 

gen D_LL = 0
replace D_LL = 1 if D_credor == 0 & D_acionista == 0 

gen D_LH = 0
replace D_LH = 1 if D_credor == 1 & D_acionista == 0 

gen D_HL = 0
replace D_HL = 1 if D_credor == 0 & D_acionista == 1 

********************************************************************************







********************************************************************************
* C�lculo das vari�veis emp�ricas
gen al1 = levat
label var al1 "Total Debt / Total Assets"

* Oportunidade de crescimento 
gen OC = mktbook
label var OC "Op. Cresc."

* Tamanho
gen tamanho = log(salesg)
label var tamanho "Tamanho"

* ROA
gen ROA = roapl
label var ROA "Lucratividade"

* Tangibilidade
gen tangibilidade = fat/assetst 			
label var tangibilidade "Tangibilidade"
	
* Loss carryback
gen carryloss = 0
replace carryloss = 1 if country=="Canad�"
replace carryloss = 1 if country=="Fran��a"
replace carryloss = 1 if country=="Alemanha"
replace carryloss = 1 if country=="Irlanda"
replace carryloss = 1 if country=="Pa�ses Baixos"
replace carryloss = 1 if country=="Reino Unido"
replace carryloss = 1 if country=="Noruega"
replace carryloss = 1 if country=="EUA"


* Qtde empresas por pa�s
sort country id_firm year
bys id_firm : egen qtde_firms = count(id_firm) if id_firm != id_firm[_n-1]
bysort country : egen total_firms = sum(qtde_firms) 
label var total_firms "Quantidade de empresas no pa�s"

********************************************************************************













********************************************************************************
* Filtros na base de dados

foreach x in 	sharequity sharfunds mktcap {
bys id_firm : egen MIN`x' = min(`x')
}

* Exclus�o PL < 0	
drop if MINsharequity <=0 
drop if MINsharfunds <=0 

* Exclus�o capital stock < 5mi	
drop if MINmktcap <= 5000000 

drop MINsharequity MINsharfunds MINmktcap

* Exclus�o crescimento de ativos e vendas > 100 % & < 100&
xtset id_firm year
by id_firm: gen ag = (assetst - L.assetst) / assetst
by id_firm: gen sg = (salesg - L.salesg) / salesg

sum ag sg , d

foreach x in 	ag sg mktbook {
bys id_firm : egen MIN`x' = min(`x')
bys id_firm : egen MAX`x' = max(`x')
}
*
drop if MAXag >= 1
drop if MINag <= -1
drop if MAXsg >= 1
drop if MINsg <= -1


* Tobin's Q > 10 ou negativo
drop if MAXmktbook >= 10
drop if MINmktbook <= 0
sum ag sg mktbook , d

* Time series das empresas abaixo de 3 observa��es
xtset id_firm year
bys id_firm : egen filter = count(assetst) if assetst != .
by id_firm: replace filter = cond(L.filter ==. , 1 , L.filter + 1) if filter~=.
by id_firm : egen max_filter = max(filter)
drop if max_filter <= 3

* Winsoriza��o
foreach x in al1 OC ROA tangibilidade  {
winsor `x' , gen(w`x') p(0.01)
}
*
la var wal1  "Alavancagem"
la var wOC "Op. de Crescimento"
la var wtangibilidade "Tangibilidade"
la var wROA "Lucratividade"

* Cria��o vari�vel Incerteza do neg�cio, utilizando ROA winsorizado
sort country year 
sort id_firm
by id_firm: egen desvio_padrao_ROA_w = sd(wROA)
label var desvio_padrao_ROA_w "Incerteza do neg�cio"


* Defini��o de labels adicionais
la var CorporateTax 	"IR Empresarial"
la var cresc_GDP 		"Crescimento PIB"
la var carryloss 		"Loss Carryback"
la var Inflacao 		"Infla��o"
********************************************************************************







********************************************************************************
* Defini��o Emergentes vs. Desenvolvidos
gen emerging = 0
replace emerging=1 if country=="�frica do Sul"
replace emerging=1 if country=="Argentina"
replace emerging=1 if country=="Brasil"
replace emerging=1 if country=="Col�mbia"
replace emerging=1 if country=="Equador"
replace emerging=1 if country=="Egito"
replace emerging=1 if country=="Filipinas"
replace emerging=1 if country=="Gr�cia"
replace emerging=1 if country=="Jord�nia"
replace emerging=1 if country=="Indon�sia"
replace emerging=1 if country=="Mal�sia"
replace emerging=1 if country=="M�xico"
replace emerging=1 if country=="Peru"
replace emerging=1 if country=="Sri Lanka"
replace emerging=1 if country=="Tail�ndia"
replace emerging=1 if country=="Turquia"
la var emerging "Emergentes"

drop id
sort country -year
bys id_country  : gen id = _n

* Cria��o gr�fico Emergentes vs. Desenvolvidos
twoway (scatter fcred fshar if id==1 & emergin==0,mlabel(country) mlabv(pos) mlabp(6) mlabsize(vsmall) msize(small) msymbol(o) yline($medcred) xline($medshar)  ytitle(Direito dos Credores) xtitle(Prote��o aos Acionistas Minorit�rios) graphregion(color(white)) xsc(r(0.5(.25)4)) xlabel(0.5(0.5)4) ysc(r(1(0.25)4.5)) ylabel(1(0.5)4.5,nogrid) text(4.4 3.8 "HH", place(e)) text(4.4 0.6 "LH", place(e)) text(1.1 0.6 "LL", place(e)) text(1.1 3.8 "HL", place(e)))   (scatter fcred fshar if id==1 &emerging==1, mlabel(country) mlabv(pos) mlabp(12) mlabsize(vsmall) msize(small) msymbol(o) )  ,legend(label(1 "Desenvolvidos") label(2 "Emergentes")) 
graph save "1RAC 2019 0109 Graph Emergentes" , replace

* Defini��o acima e abaixo da m�dia de alavancagem
bys country :  egen levm = mean(wal1)
gen levUP = 0
sum levm if id==1
replace levUP = 1 if levm>`r(mean)'

* Cria��o gr�fico acima vs. abaixo da m�dia de alavancagem

twoway (scatter fcred fshar if id==1 & levUP==1,mlabel(country) mlabv(pos) mlabp(6) mlabsize(vsmall) msize(small) msymbol(o) yline($medcred) xline($medshar)  ytitle(Direito dos Credores) xtitle(Prote��o aos Acionistas Minorit�rios) graphregion(color(white)) xsc(r(0.5(.25)4)) xlabel(0.5(0.5)4) ysc(r(1(0.25)4.5)) ylabel(1(0.5)4.5,nogrid) text(4.4 3.8 "HH", place(e)) text(4.4 0.6 "LH", place(e)) text(1.1 0.6 "LL", place(e)) text(1.1 3.8 "HL", place(e)))   (scatter fcred fshar if id==1 &levUP==0    , mlabel(country) mlabv(pos) mlabp(12) mlabsize(vsmall) msize(small) msymbol(o) )  , legend(label(1 "Alavancagem > M�dia") label(2 "Alavancagem < M�dia")) 
graph save "1RAC 2019 0109 Graph Alav" , replace

window manage close graph   
********************************************************************************








********************************************************************************
* Globals e descritivas

gen int_HH = wtangibilidade*D_HH
gen int_HL = wtangibilidade*D_HL
gen int_LH = wtangibilidade*D_LH

la var int_LH "Tangibilidade x D_LH"
la var int_HL "Tangibilidade x D_HL"
la var int_HH "Tangibilidade x D_HH"

* Defini��o de globals para as vari�veis de interesse
global mainFIRM 	wOC 		tamanho 		wROA 		desvio_padrao_ROA_w 	wtangibilidade
global mainMACROl 	carryloss  CorporateTax     cresc_GDP 	Inflacao
global mainTD 		D_LH 	   D_HL  D_HH
global mainINT 		int_LH int_HL int_HH 

* Estat�sticas descritivas
egen sampleF = rowmiss(wal1 $mainFIRM $mainMACROl fshar fcred) 
global if if sampleF==0
estpost tabstat  wal1  $mainFIRM $mainMACROl fshar fcred $if , casewise c(s) s(min p25 p50 p75 max sd n) 

estpost summarize wal1 $mainFIRM $mainMACROl fshar fcred $if , listwise d
esttab ., cells("min(fmt(3)) mean(fmt(3)) p50(fmt(3)) max(fmt(3)) sd(fmt(3)) count(fmt(0))") noobs label nonumber


* Tabela de Correla��o
estpost correlate wal1 $mainFIRM $mainMACROl fshar fcred  , matrix listwise
esttab . , unstack not compress eqlabels("1" "2" "3""4""5""6""7""8""9""10")  label varwidth(18)





********************************************************************************
* Estima��o do modelo emp�rico

* A) Modelo principal

xtset id_firm year
estimates clear
eststo: qui reg wal1  $mainFIRM $mainMACROl $mainTD $mainINT					, vce(cluster country)
eststo: qui reg wal1  $mainFIRM $mainMACROl $mainTD $mainINT i.year				, vce(cluster country)
eststo: qui reg wal1  $mainFIRM $mainMACROl $mainTD $mainINT i.id_ind		    , vce(cluster country)
eststo: qui reg wal1  $mainFIRM $mainMACROl $mainTD $mainINT i.year i.id_ind   	, vce(cluster country)

esttab  								, label compress brackets nonumber drop(1* 2* 3* 4* 5* 6* 7* 8* 9*) b(%3.2f) t(%3.2f) scalars("r2 R-Quadrado" "FEAno" "FEindustria" ) nogaps varwidth(20)
esttab using "1RAC 2019 0109 table4.rtf", label compress brackets nonumber drop(1* 2* 3* 4* 5* 6* 7* 8* 9*) b(%3.2f) t(%3.2f) scalars("r2 R-Quadrado" "FEAno" "FEindustria" ) nogaps varwidth(20) replace

* Apresenta��o dos betas na tela do Stata
di _b[D_HL] " | " _b[D_HH]
di 0 		" | " _b[D_LH]


* B) Teste de Robustez
global legal French German Scandinavian
global rob if country ~= "Coreia do Sul" & country ~= "Jap�o"

estimates clear
eststo: qui reg al1 $mainFIRM 			   		 	$mainTD $mainINT i.year i.id_ind 		, vce(cluster country)
eststo: qui reg al1 $mainFIRM $mainMACROl emerging 	$mainTD $mainINT i.year i.id_ind 		, vce(cluster country)
eststo: qui reg al1 $mainFIRM $mainMACROl $legal 	$mainTD $mainINT i.year i.id_ind 		, vce(cluster country)
eststo: qui reg al1 $mainFIRM $mainMACROl 			$mainTD $mainINT i.year i.id_ind $rob	, vce(cluster country)

esttab  								, label compress brackets order($mainFIRM $mainMACROl $mainTD $mainINT) nonumber drop(1* 2* 3* 4* 5* 6* 7* 8* 9*) b(%3.2f) t(%3.2f) scalars("r2 R-Quadrado" "FEAno" "FEindustria" ) nogaps varwidth(20)
esttab using "1RAC 2019 0109 table5.rtf", label compress brackets order($mainFIRM $mainMACROl $mainTD $mainINT) nonumber drop(1* 2* 3* 4* 5* 6* 7* 8* 9*) b(%3.2f) t(%3.2f) scalars("r2 R-Quadrado" "FEAno" "FEindustria" ) nogaps varwidth(20) replace


* C) Teste de Robustez weighted by variance (n�o apresentado no artigo)

bys country : egen n = count(year) if sampleF==0

xtset id_firm year
estimates clear
eststo: qui reg wal1  $mainFIRM $mainMACROl $mainTD $mainINT				 	[pw = n]	, vce(cluster country)
eststo: qui reg wal1  $mainFIRM $mainMACROl $mainTD $mainINT i.year				[pw = n]	, vce(cluster country)
eststo: qui reg wal1  $mainFIRM $mainMACROl $mainTD $mainINT i.id_ind		 	[pw = n]   	, vce(cluster country)
eststo: qui reg wal1  $mainFIRM $mainMACROl $mainTD $mainINT i.year i.id_ind   	[pw = n]	, vce(cluster country)

esttab  								, label compress brackets nonumber drop(1* 2* 3* 4* 5* 6* 7* 8* 9*) b(%3.2f) t(%3.2f) scalars("r2 R-Quadrado" "FEAno" "FEindustria" ) nogaps varwidth(20)
esttab using "1RAC 2019 0109 table6.rtf", label compress brackets nonumber drop(1* 2* 3* 4* 5* 6* 7* 8* 9*) b(%3.2f) t(%3.2f) scalars("r2 R-Quadrado" "FEAno" "FEindustria" ) nogaps varwidth(20) replace 

********************************************************************************




********************************************************************************
* Informa��es adicionais para inclus�o no artigo

* N�mero de observa��es por pa�s
egen filter2 = group(id_firm) if sampleF==0
sum filter2
tab country if sampleF==0

* Correla��o dos fatores entre os pa�ses
pwcorr fshar fcred if id==1 ,obs

* Apresenta��o dos valores dos �ndices e sub-�ndices por pa�s
estpost tabstat f_creditor_rights_rev f_legalreserve f_recovery_rate f_enforcement f_sharing fcred f_mdiv f_selfdealing f_adri_rev f_disclosure f_standard fshar, by(country) nototal


* closing and translating log
log close
translate "1RAC 2019 0109.smcl" "1RAC 2019 0109.txt" , replace
translate "1RAC 2019 0109.smcl" "1RAC 2019 0109.pdf" , replace
